package Algorithm.dynamicProgramming.introduct;

/**
 * 1143. 最长公共子序列 https://leetcode.cn/problems/longest-common-subsequence/
 * 题目简述：给定两个字符串text1和text2，返回这两个字符串的最长公共子序列的长度。
 * 参考：https://www.bilibili.com/video/BV1ey4y1d7oD/
 */
public class LongestCommonSubsequence {

    /**
     * 思路：动态规划 对于可能是动态规划的题，直接先按所需的结果来按步骤写定义
     * 1. 定义dp：dp[i][j]为s1中前i个字符和s2中前j个字符的LCS
     * 2. 状态转移公式：分为两种情况
     *          （1）当s1[i] = s2[j]时，dp[i][j] = dp[i-1][j-1] + 1
     *          (2) 当s1[i] ≠ s2[j]时，dp[i][j] = max(dp[i-1][j], dp[i][j-1])
     * 3. 初始化：dp[i][0] = 0, dp[0][j] = 0;
     */
    public int longestCommonSubsequence(String text1, String text2) {
        int[][] dp = new int[text1.length() + 1][text2.length() + 1];
        for (int i = 1;i <= text1.length();i++) {
            for (int j = 1;j <= text2.length();j++) {
                if (text1.charAt(i-1) == text2.charAt(j-1))
                    dp[i][j] = dp[i-1][j-1] + 1;
                else
                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
            }
        }
        return dp[text1.length()][text2.length()];
    }



    public static void main(String[] args) {
        new LongestCommonSubsequence().longestCommonSubsequence("abc", "abc");
    }
}
